package com.hstc.util;

import javax.mail.*;
import java.util.Properties;

/**
 * @auther 倪万佳
 * @date 2018/11/2 10:47
 * 接收邮件的类
 */
public class POP3Help {

    public static Folder getFolder(String host, String username, String password) {
         Properties prop = new Properties();
         prop.setProperty("mail.store.protocol", "pop3");
         prop.setProperty("mail.pop3.host", host);
        Session mailSession = Session.getDefaultInstance(prop, null);
        mailSession.setDebug(false);
        try{
            Store store = mailSession.getStore("pop3");
            store.connect(host, username, password);
            Folder folder = store.getFolder("inbox");
            folder.open(Folder.READ_WRITE);
            return folder;

        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Object handleText(Message msg) throws Exception{
        if(!msg.isMimeType("multipart/mixed")) {
          return  msg.getContent();
        }else {
            //查找并输出邮件中的邮件正文
            Multipart mp = (Multipart) msg.getContent();
            int bodynum = mp.getCount();
            for(int i = 0; i < bodynum; i++) {
                BodyPart bodyPart = mp.getBodyPart(i);
                /**
                 * MIME消息头中不包含disposition字段，
                 * 并且MIME消息类型不为mixed时，
                 * 表示当前获得的MIME消息为邮件正文
                 */
                if(!bodyPart.isMimeType("multipart/mixed") && bodyPart.getDisposition() == null) {
                    return  bodyPart.getContent();
                }
            }
            return "";
        }

    }


}
